import React, { useState,useEffect  } from 'react';
import { useHistory } from "react-router-dom";
import {
  List, InputItem, Picker, Modal, DatePicker, Toast,
} from 'antd-mobile';
import Btn from "../../../components/btn/Btn";
import Textarea from "../../../components/textarea/Textarea";
// 数字编码，门诊号，客管，新增日期选择器
import './edit.less';
import http from "../../../model/http";
// import {sendMsg} from "../../../model/code";
import province from "../../../model/province";
import logo from '../../../libs/img/logo/logo';
import ListCheckbox from '../../../components/listCheckbox/ListCheckbox'

let Item = List.Item,
  alert = Modal.alert,
  // user = JSON.parse(localStorage.getItem('user'))
  now = e=>e?new Date(e):new Date(),
  pp = '请输入...',
  pp2 = '点击选择';


function Edit() {

  const history = useHistory(),
      query = http.useQuery(),
      type = query.get('type'),
      outUserId = query.get('outUserId'),
     [modal,setModal] = useState(false),
     [data,setData] = useState({
      informedway:[], //来源
      identity_all:[], //身份
      economic_all:[], //经济
      marry_all:[], //婚姻
      body_all:[], //身材
      skin_all:[], //皮肤
      face_all:[], //脸型
      city:[],
      province:[],
      sex:[{label:'男',value:'1'},{label:'女',value:'2'},]
    }),
    [info,setInfo] = useState({
      birthday:'',
      sex:[]
    }),
    [moreInfo,setMoreInfo] = useState({
      provinceId:[],
      cityId:[],
      districtId:[],
      body: [],
      economic: [],
      identity: [],
      informedWayId: [],
      marry: [],
      skin: [],
      remark:''
    });
  console.log(history)
  useEffect(()=>{
    http.post('/customer/customerDetail',{
      customerCrmId:history.location.state.customerCrmId
    }).then(e=> {
        let i = e.baseInfo[0], m = e.moreInfo[0];
        if(type==='add') {
          setData({...data,...e})
          return;
        }

      i.sex = [i.sex]
      i.birthday = now(i.birthday.replace(/-/g, '/'));
      e.skin_all.forEach(v => {
        v.checked = m.skin.value.includes(v.value) ? true : false;
      })

      let _moreInfo = {
        body: [m.body.value],
        economic: [m.economic.value],
        identity: [m.identity.value],
        marry: [m.marry.value],
        remark: m.remark,
        skin: e.skin_all.filter(v => v.checked),
        informedWayId: m.informedWayId.split(',').map(i => i - 0)
      };
      setCityInfo({_moreInfo,e})

      })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  },[])



  let setCityInfo = async obj => {
    let {_moreInfo,e} = obj, c = e.moreInfo[0].cityinfo;
    if(c.provinceId){
      _moreInfo.provinceId = [c.provinceId-0];
      let city = await http.post('/customer/getRegionInfo',{
        type:2,parentId:c.provinceId
      })
      console.log('city');
      data.city = city.data.map(i=>{i.value=i.id;i.label=i.regionName;return i});
      if(c.cityId){
        _moreInfo.cityId = [c.cityId-0];
        let province = await http.post('/customer/getRegionInfo',{type:3,parentId:c.cityId})
        console.log('province');
        data.district = province.data.map(i=>{i.value=i.id;i.label=i.regionName;return i});
        if(c.districtId){
          _moreInfo.districtId = [c.districtId-0];
        }
      }
    }

    setInfo({...info,...e.baseInfo[0]})
    setMoreInfo({...moreInfo,..._moreInfo})
    setData({...data,...e})
  }

  // 基础信息
  let setInfoVal = (v,t)=>{setInfo({...info, [t]:v})};
  // 更多信息
  let setMoreInfoVal = (v,t)=>{setMoreInfo({...moreInfo, [t]:v})};

  // 皮肤-多选
  let setSkinAllVal = (_data,_selectData)=>{
    setData({...data});
    moreInfo.skin = _selectData;
    setMoreInfo({...moreInfo});
  }

  // 生日
  let setUserDateVal = e=>{
    let ageTime = now(e).getTime() - now().getTime();
    let age = 0 - Math.ceil(ageTime/31536000000)
    setInfo({...info,age,birthday:e})
  }
  // 选择省份
  let setProvinceVal = async v =>{
    console.log('aaa',v)

    setMoreInfo({
      ...moreInfo,
      provinceId:v,
      cityId:[],
      districtId:[]
    })

    let city = await http.post('/customer/getRegionInfo',{type:2,parentId:v[0]})
    console.log(city.data);
    city.data.forEach(i=>{i.value = i.id;i.label = i.regionName})
    setData({...data,city:city.data})
  }

  // 选择城市
  let setCityVal = async v =>{
    setMoreInfo({...moreInfo, cityId:v, districtId:[]})

    let district = await http.post('/customer/getRegionInfo',{type:3,parentId:v[0]})
    console.log('district');
    district.data.forEach(i=>{i.value = i.id;i.label = i.regionName})
    setData({...data,district:district.data})
  }

  // 修改
  const warn = e => {
    let t = type==='add'?'新增':'确认';
    alert('提示', '是否'+t, [{ text: '取消'}, { text: t, onPress: submit }])
  }
  // 发送消息
  // const warn2 = e => {
  //   alert('提示', '确认发送', [
  //     {text:'取消'}, {text:'发送', onPress(){
  //         const link = `${window.location.origin}/outUser/binding?hosId=${window._user.hosId}&crmId=${history.location.state.customerCrmId}`,
  //             title= "客户信息确认", desc= "请确认您的建档信息，涉及您的隐私请确保本人查看";
  //         sendMsg(link,title,desc);
  //     }},
  //   ])
  // }
  // 新增
  const warn3 = e=>{
    if(!info.customerName || !/^1[3456789]\d{9}$/.test(info.mobileNo1)){
      Toast.fail('姓名或手机号不正确')
    }else {
      warn()
    }
  }

  const submit = async ()=>{
    const _moreInfo={
      remark:moreInfo.remark||'',
      cityinfo: moreInfo.provinceId+ ','+moreInfo.cityId.toString()+','+ moreInfo.districtId.toString()
    };

    moreInfo.skin = data.skin_all.filter(v=>v.checked).map(v=>v.value)
    Object.keys(moreInfo).forEach(v=>{if(v !== 'remark') _moreInfo[v]=moreInfo[v].join()})

    let _info = {
      ...info, sex:info.sex[0]||'', age:info.age?(info.age+''):'',
      birthday:info.birthday ? info.birthday.toLocaleDateString().replace(/\//g,'-') : ''
    }

    let _url = '/customer/'+ (type==='add'?'newCustomerInfo':'updateCustomerDetail');
    // 并且修改更多信息
    // console.log(JSON.stringify({baseInfo:_info, moreInfo:_moreInfo, outUserId:outUserId}));
    // let ok  = await http.post_json(_url,{baseInfo:_info, moreInfo:_moreInfo, outUserId:outUserId})
    // console.log(window.localStorage.getItem('user'))
    const str_user = window.localStorage.getItem('user')
    const user = JSON.parse(str_user)
    let ok  = await http.outPost('/customer/updateCustomerDetailBind',{
      crmId: user.managerId,
      hosId: user.hosId,
      userId: user.userid,
      customerCrmId:history.location.state.customerCrmId,
      outUserId:outUserId
    })
    ok.code !== -1 && Toast.success( '成功')
  }

  // let test = e=>{
  //   console.log(e)
  //   // setSexValue(e)
  // }

  return (
    <div className='v-user-edit'>
      <List className='g-p5-10 g-bg-f g-bdrs12'>
        <div className='v-title'>
          <img className='v-logo g-r'
               src={logo[window._user.hosId]}
               alt="logo"/>
          基础信息
        </div>

        {type === 'add' ? (
          <>
            <InputItem onChange={v=>setInfoVal(v,'customerName')}
                       value={info.customerName}
                       placeholder={pp}>顾客姓名</InputItem>
            <InputItem onChange={v=>setInfoVal(v,'mobileNo1')}
                       value={info.mobileNo1}
                       placeholder={pp}>手机号</InputItem>
          </>
          ):(<Item extra={info.customerName}>顾客姓名</Item>)
        }

        <DatePicker extra={pp}
                    value={info.birthday}
                    onChange={setUserDateVal}
                    format='YYYY-MM-DD'
                    minDate={now(1)}
                    maxDate={now()}
                    mode='date'>
          <Item>生日</Item>
        </DatePicker>
        <InputItem type='number'
                   onChange={v=>setInfoVal(v,'age')}
                   value={info.age}
                   placeholder={pp}>年龄</InputItem>

        <Picker data={data.sex} cols={1}
                value={info.sex}
                onChange={v=>setInfoVal(v,'sex')}
                extra={pp2}>
          <Item>性别</Item>
        </Picker>

        {info.mobileNo1 && type !== 'add' && (<Item extra={info.mobileNo1}>手机号</Item>)}
        {info.mobileNo2 && (<Item extra={info.mobileNo2}>手机号2</Item>)}
        {info.mobileNo3 && (<Item extra={info.mobileNo3}>手机号3</Item>)}
        {info.mobileNo4 && (<Item extra={info.mobileNo4}>手机号4</Item>)}

        <InputItem onChange={v=>setInfoVal(v,'customerIdCardNo')}
                   value={info.customerIdCardNo}
                   placeholder={pp}>身份证</InputItem>
        {type==='add'||(
          <>
            <Item extra={info.customerCrmId}>数字编码</Item>
            <Item extra={info.mzcode}>门诊号</Item>
            <Item extra={'[网电]'+info.dwname} wrap>所属客管</Item>
            <Item extra={'[现场]'+info.xcname} wrap>&emsp;</Item>
          </>
        )}

      </List>

      <List className='g-mt10 g-p5-10 g-bg-f g-bdrs12'>
        <div className='v-title'>
          更多信息
          <span className='g-f12 g-c8'>(仅咨询师可见，对顾客不可见)</span>
        </div>

        <Picker data={data.informedway} cols={2}
                value={moreInfo.informedWayId}
                extra={pp2}
                format={e=>e.join('-')}
                onChange={v=>setMoreInfoVal(v,'informedWayId')}>
          <Item>来源</Item>
        </Picker>
        <div className='wrap'>
          <Picker data={province} cols={1}
                  value={moreInfo.provinceId}
                  extra={pp2}
                  onChange={setProvinceVal}>
            <Item>省份</Item>
          </Picker>
        </div>
        <div className='wrap'>
          <Picker data={data.city} cols={1}
                  value={moreInfo.cityId}
                  extra={pp2}
                  onChange={setCityVal}>
            <Item>城市</Item>
          </Picker>
        </div>
        <div className='wrap'>
          <Picker data={data.district} cols={1}
                  value={moreInfo.districtId}
                  extra={pp2}
                  onChange={v=>setMoreInfoVal(v,'districtId')}>
            <Item>区县</Item>
          </Picker>
        </div>

        <Picker data={data.identity_all} cols={1}
                value={moreInfo.identity}
                extra={pp2}
                onChange={v=>setMoreInfoVal(v,'identity')}>
          <Item>身份</Item>
        </Picker>
        <Picker data={data.economic_all} cols={1}
                value={moreInfo.economic}
                extra={pp2}
                onChange={v=>setMoreInfoVal(v,'economic')}>
          <Item>经济程度</Item>
        </Picker>

        <Picker data={data.marry_all} cols={1}
                value={moreInfo.marry}
                extra={pp2}
                onChange={v=>setMoreInfoVal(v,'marry')}>
          <Item>婚姻状况</Item>
        </Picker>
        <Picker data={data.body_all} cols={1}
                value={moreInfo.body}
                extra={pp2}
                onChange={v=>setMoreInfoVal(v,'body')}>
          <Item>体型状态</Item>
        </Picker>

        <Item extra={moreInfo.skin.map(v=>v.label).join() || pp2}
              onClick={()=>setModal(true)}>
          皮肤状态
        </Item>

        <Item>
          <Textarea autoHeight t='备注'
                    onChange={v=>setMoreInfoVal(v,'remark')}
                    value={moreInfo.remark}
                    placeholder={pp}/>
        </Item>

      </List>
      <div className='g-flex g-between'>
        {
          type==='add'?
          (<Btn type='primary' onClick={warn3}>新增</Btn>):
          (<Btn type='primary' size='samll' onClick={warn}>确认并绑定</Btn>)
        }
      </div>

      <ListCheckbox data={data.skin_all} visible={modal} setVisible={setModal} afterClose={setSkinAllVal} />
    </div>
  )
}

export default Edit;

/*
 * <>
              <Header type='primary' size='samll' onClick={warn2}>发送给顾客</Header>
              <span>&emsp;&emsp;</span>
              <Header type='warning' size='samll' onClick={warn}>确认并绑定</Header>
            </> 
 */
